package com.item.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.item.service.ManagerService;
import com.item.service.MessagesService;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author XXDLD
 */
@ServerEndpoint(value = "/imserver/{username}")
@Component
public class WebSocketServer {

    // 静态 ManagerService 实例
    private static MessagesService messagesService;
    private static ManagerService managerService;

    // 静态 setter 方法用于依赖注入
    @Autowired
    public void setMessagesService(MessagesService messagesService) {
        WebSocketServer.messagesService = messagesService;
    }
    @Autowired
    public void setManagerService(ManagerService managerService) {
        WebSocketServer.managerService = managerService;
    }


    // 初始化日志记录器
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    // 使用ConcurrentHashMap存储会话信息
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessionMap.put(username, session);
        log.info("有新用户加入，username={}, 当前在线人数为：{}", username, sessionMap.size());
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        log.info("服务端收到用户{}的消息:{}", username, message);

        // 解析收到的消息
        JSONObject obj = JSONUtil.parseObj(message);
        String type = obj.getStr("type");

        // 消息保存到数据库
        saveMessagesToDatabase(obj);

        if ("notifyManager".equals(type)) {
            String manager = obj.getStr("manager");
            sendMessageToManager(manager, message, session);
        } else if ("notifyUser".equals(type)) {
            String userName = obj.getStr("userName");
            sendMessageToManager(userName, message, session);
        } else if ("chat".equals(type)) {
            String text = obj.getStr("text");

            if (text == null || text.trim().isEmpty()) {
                text = "empty";
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("type", "chat");
            jsonObject.set("from", username);
            jsonObject.set("text", text);

            broadcastMessage(jsonObject.toString());
            log.info("{}发送的消息：{}", username, jsonObject.toString());
        }
    }

    private void saveMessagesToDatabase(JSONObject message) {
        String fromUserName = message.getStr("from");
        String text = message.getStr("text");
        String type = message.getStr("type");
        String toUserName = message.getStr("to");
        if (!fromUserName.isEmpty() && toUserName!=null){
            messagesService.putMessagesByuserName(fromUserName,text,type,toUserName);
        }
    }

    private void sendMessageToManager(String manager, String message, Session userSession) {
        Session managerSession = sessionMap.get(manager);
        if (managerSession != null) {
            sendMessage(message, managerSession);
        } else {
            log.warn("管理员{}未连接", manager);
            // 返回管理员未连接的消息给用户
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("type", "error");
            jsonObject.set("from", "server");
            jsonObject.set("text", "管理员未连接");
            sendMessage(jsonObject.toString(), userSession);
        }
    }

    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    private void broadcastMessage(String message) {
        for (Session session : sessionMap.values()) {
            try {
                log.info("服务端给客户端[{}]发送消息{}", session.getId(), message);
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.error("服务端发送消息给客户端失败", e);
            }
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {

        if (username.equals("manager1")){
            managerService.updateOffByManagerName(username);
        }
        if (username.equals("manager2")){
            managerService.updateOffByManagerName(username);
        }
        if (username.equals("manager3-1")){
            managerService.updateOffByManagerName(username);
        }

        sessionMap.remove(username);

        log.info("有一连接关闭，移除username={}的用户session, 当前在线人数为：{}", username, sessionMap.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

}
